#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "organdef.h"
#include "welltempMore.h"
#include "key2wheel.h"
#include "devdsp.h"
#include "playsound.h"
#include "playnote.h"
#include "drawbar.h"
#include "gentone.h"

#define SAMPLE_RATE 44100
#define BUF_SIZE 19200


int fd;
short *buf1, *buf2, *buf3;
int buf_flag;
int gen_flag;
int on_sig;
double wheel_v[92];
int ppos[92];
int key_status[62];
double drawbar_level[] = { 0.0, 1.0/5120, 2.0/5120, 3.0/5120, 4.0/5120, 5.0/5120, 6.0/5120, 7.0/5120, 8.0/5120};
int drawbar[9] = {8, 8, 8, 4, 2, 1, 3, 4, 5};

void NoteOn(int note)
{
	PlayNote(note, 61, key_status);
	CalculateWheelV( 61, key_status, (int*)key2wheel, 91, wheel_v, 9, drawbar, drawbar_level);
}
void NoteOff(int note)
{
	StopNote(note, 61, key_status);
	CalculateWheelV( 61, key_status, (int*)key2wheel, 91, wheel_v, 9, drawbar, drawbar_level);
}
void ThreadSimpleSong(void *arg)
{
	NoteOn(25);
	sleep(2);
	NoteOn(29);
	sleep(2);
	NoteOn(32);
	sleep(5);
	NoteOff(25);
	NoteOff(29);
	NoteOff(32);

	on_sig = 0;
}

void ThreadPlaySound(void *arg)
{
    int fd = InitDevDsp(SAMPLE_RATE);
    PlaySound( fd, BUF_SIZE, buf1, buf2, &buf_flag, &gen_flag, &on_sig);
    EndDevDsp(fd);
}

void ThreadGenTone(void *arg)
{
	GenTone(91, wheels, lens, ppos, wheel_v,
		BUF_SIZE, buf1, buf2, &buf_flag,&gen_flag, &on_sig);
}


int main(int argc, char *argv[])
{


	buf1= (smpl_t *) malloc ( BUF_SIZE * sizeof(smpl_t));
	buf2= (smpl_t *) malloc ( BUF_SIZE * sizeof(smpl_t));
	buf3= (smpl_t *) malloc ( BUF_SIZE * sizeof(smpl_t));


	pthread_t tplay, tgen, tsong;

	//int ret;

	on_sig = 1;
	pthread_create( &tgen, NULL, (void*) ThreadGenTone, NULL);
    pthread_create( &tplay, NULL, (void*) ThreadPlaySound, NULL);
	pthread_create( &tsong, NULL, (void*) ThreadSimpleSong, NULL);

    pthread_join( tgen, NULL);
    pthread_join( tplay, NULL);
    pthread_join( tsong, NULL);



	free(buf1);
	free(buf2);
	free(buf3);

	return 0;
}

